<template>
	<view class="content">
		<!-- 顶部筛选导航：综合/销量/价格；支持吸顶定位与 H5 页面头部偏移 -->
		<view class="navbar" :style="{position:headerPosition,top:headerTop}">
			<!-- 综合排序：filterIndex=0 -->
			<view class="nav-item" :class="{current: filterIndex === 0}" @click="tabClick(0)">
				综合排序
			</view>
			<!-- 销量优先：filterIndex=1 -->
			<view class="nav-item" :class="{current: filterIndex === 1}" @click="tabClick(1)">
				销量优先
			</view>
			<!-- 价格排序：filterIndex=2；priceOrder 1=升序 2=降序，对应上下箭头激活 -->
			<view class="nav-item" :class="{current: filterIndex === 2}" @click="tabClick(2)">
				<text>价格</text>
				<view class="p-box">
					<text :class="{active: priceOrder === 1 && filterIndex === 2}" class="yticon icon-shang"></text>
					<text :class="{active: priceOrder === 2 && filterIndex === 2}" class="yticon icon-shang xia"></text>
				</view>
			</view>
			<!-- 打开分类侧边面板 -->
			<text class="cate-item yticon icon-fenlei1" @click="toggleCateMask('show')"></text>
		</view>
		<!-- 商品瀑布宫格列表：点击 item 进入详情页 -->
		<view class="goods-list">
			<view 
				v-for="(item, index) in goodsList" :key="index"
				class="goods-item"
				@click="navToDetailPage(item)"
			>
				<view class="image-wrapper">
					<image :src="item.image" mode="aspectFill"></image>
				</view>
				<text class="title clamp">{{item.title}}</text>
				<!-- <view class="price-box">
					<text class="price">{{item.price}}</text>
					<text>已售 {{item.sales}}</text>
				</view> -->
			</view>
		</view>
		<!-- 上拉加载/无更多 状态展示 -->
		<uni-load-more :status="loadingType"></uni-load-more>
		
		<!-- 分类侧滑遮罩：cateMaskState 0=隐藏 1=显示 2=过渡中；点击蒙层关闭 -->
		<view class="cate-mask" :class="cateMaskState===0 ? 'none' : cateMaskState===1 ? 'show' : ''" @click="toggleCateMask">
			<!-- 右侧分类内容区域；阻止冒泡与滚动穿透 -->
			<view class="cate-content" @click.stop.prevent="stopPrevent" @touchmove.stop.prevent="stopPrevent">
				<!-- 三级分类选择列表：cateList 为二级分类，child 为对应三级 -->
				<scroll-view scroll-y class="cate-list">
					<view v-for="item in cateList" :key="item.id">
						<!-- 二级分类标题 -->
						<view class="cate-item b-b two">{{item.name}}</view>
						<!-- 三级分类项；高亮当前 cateId，点击切换并刷新数据 -->
						<view 
							v-for="tItem in item.child" :key="tItem.id" 
							class="cate-item b-b" 
							:class="{active: tItem.id==cateId}"
							@click="changeCate(tItem)">
							{{tItem.name}}
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
		
	</view>
</template>

<script>
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
	export default {
		components: {
			uniLoadMore	
		},
		data() {
			return {
				cateMaskState: 0, //分类面板展开状态
				headerPosition:"fixed",
				headerTop:"0px",
				loadingType: 'more', //加载更多状态
				filterIndex: 0,
				fid: 0, // 已选一级分类id
				sid: 0, // 已选二级分类id
				cateId: 0, // 已选三级分类id（tid）
				priceOrder: 0, //1 价格从低到高 2价格从高到低
				cateList: [],
				goodsList: [],
				currentPage: 1, // 当前页码
				pageSize: 10 // 每页数量
			};
		},
		
		onLoad(options){
			// #ifdef H5
			this.headerTop = document.getElementsByTagName('uni-page-head')[0].offsetHeight+'px';
			// #endif
			this.fid = Number(options.fid || 0);
			this.sid = Number(options.sid || 0);
			this.cateId = Number(options.tid || 0);
			this.loadCateList(this.fid, this.sid);
			this.loadData();
		},
		onPageScroll(e){
			//兼容iOS端下拉时顶部漂移
			if(e.scrollTop>=0){
				this.headerPosition = "fixed";
			}else{
				this.headerPosition = "absolute";
			}
		},
		//下拉刷新
		onPullDownRefresh(){
			this.loadData('refresh');
		},
		//加载更多
		onReachBottom(){
			this.loadData();
		},
		methods: {
			//加载分类
			async loadCateList(fid, sid){
				try {
					// 调用后端API获取层级分类结构
					let response = await this.$api.getCategoryChildren(fid);
					// 从响应中提取data字段
					this.cateList = response && response.data ? response.data : response;
				} catch (error) {
					console.error('加载分类数据失败:', error);
					this.$api.msg('加载分类数据失败');
				}
			},
			//加载商品 ，带下拉刷新和上滑加载
			async loadData(type='add', loading) {
				try {
					//没有更多直接返回
					if(type === 'add'){
						if(this.loadingType === 'nomore'){
							return;
						}
						this.loadingType = 'loading';
					}else{
						this.loadingType = 'more';
						this.currentPage = 1; // 刷新时重置页码
					}

					// 构建请求参数
					let params = {
						pageNum: this.currentPage,
						pageSize: this.pageSize,
						sortType: this.filterIndex, // 0=综合，1=销量，2=价格
						priceOrder: this.priceOrder  // 1=升序，2=降序
					};

					// 如果有选中的分类，添加分类筛选
					// 分类筛选优先级：tid > sid > fid
					if(this.cateId) params.tid = this.cateId;
					else if(this.sid) params.sid = this.sid;
					else if(this.fid) params.fid = this.fid;

					// 调用后端API获取商品列表
					let response = await this.$api.getSpuList(params).catch(() => undefined);

					if(type === 'refresh'){
						this.goodsList = [];
					}

					let goodsList = [];
					let hasNext = false;

					// 从响应中提取data字段 (因为request.js拦截器返回response.data)
					let pageInfo = response && response.data ? response.data : response;

					if (pageInfo && Array.isArray(pageInfo.list)) {
						// 后端返回标准分页 { list, hasNextPage }
						goodsList = pageInfo.list.map(item => ({
							id: item.id,
							image: item.mainImg,
							title: item.name,
							price: (item.priceFee / 100).toFixed(2), // 转换为元
							sales: item.sales || 0
						}))
						hasNext = !!pageInfo.hasNextPage;
					} else if (pageInfo && Array.isArray(pageInfo.records)) {
						// 兼容后端分页 { records, current, pages } 风格
						goodsList = pageInfo.records.map(item => ({
							id: item.id,
							image: item.mainImg,
							title: item.name,
							price: (item.priceFee / 100).toFixed(2),
							sales: item.sales || 0
						}))
						hasNext = pageInfo.current < pageInfo.pages;
					} else {
						// 后端不可用或数据结构不匹配，回退到本地 mock（Json.js）
						const mock = await this.$api.json('goodsList');
						goodsList = (mock || []).map(item => ({
							id: item.id,
							image: item.image,
							title: item.title,
							price: item.price,
							sales: item.sales || 0
						}))
						hasNext = false;
					}

					this.goodsList = this.goodsList.concat(goodsList);

					// 判断是否还有下一页
					this.loadingType  = hasNext ? 'more' : 'nomore';

					// 如果还有下一页，页码+1
					if(hasNext) {
						this.currentPage++;
					}

					if(type === 'refresh'){
						if(loading == 1){
							uni.hideLoading();
						}else{
							uni.stopPullDownRefresh();
						}
					}
				} catch (error) {
					console.error('加载商品数据失败:', error);
					this.$api.msg('加载商品数据失败');
					this.loadingType = 'more';
					if(type === 'refresh'){
						if(loading == 1){
							uni.hideLoading();
						}else{
							uni.stopPullDownRefresh();
						}
					}
				}
			},
			//筛选点击
			tabClick(index){
				if(this.filterIndex === index && index !== 2){
					return;
				}
				this.filterIndex = index;
				if(index === 2){
					this.priceOrder = this.priceOrder === 1 ? 2: 1;
				}else{
					this.priceOrder = 0;
				}
				uni.pageScrollTo({
					duration: 300,
					scrollTop: 0
				})
				this.loadData('refresh', 1);
				uni.showLoading({
					title: '正在加载'
				})
			},
			//显示分类面板
			toggleCateMask(type){
				let timer = type === 'show' ? 10 : 300;
				let	state = type === 'show' ? 1 : 0;
				this.cateMaskState = 2;
				setTimeout(()=>{
					this.cateMaskState = state;
				}, timer)
			},
			//分类点击
			changeCate(item){
				this.cateId = item.id;
				this.toggleCateMask();
				uni.pageScrollTo({
					duration: 300,
					scrollTop: 0
				})
				this.loadData('refresh', 1);
				uni.showLoading({
					title: '正在加载'
				})
			},
			//详情
			navToDetailPage(item){
				// 使用真实的商品ID
				let id = item.id;
				uni.navigateTo({
					url: `/pages/product/product?id=${id}`
				})
			},
			stopPrevent(){}
		},
	}
</script>

<style lang="scss">
	page, .content{
		background: $page-color-base;
	}
	.content{
		padding-top: 96upx;
	}

	.navbar{
		position: fixed;
		left: 0;
		top: var(--window-top);
		display: flex;
		width: 100%;
		height: 80upx;
		background: #fff;
		box-shadow: 0 2upx 10upx rgba(0,0,0,.06);
		z-index: 10;
		.nav-item{
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100%;
			font-size: 30upx;
			color: $font-color-dark;
			position: relative;
			&.current{
				color: $base-color;
				&:after{
					content: '';
					position: absolute;
					left: 50%;
					bottom: 0;
					transform: translateX(-50%);
					width: 120upx;
					height: 0;
					border-bottom: 4upx solid $base-color;
				}
			}
		}
		.p-box{
			display: flex;
			flex-direction: column;
			.yticon{
				display: flex;
				align-items: center;
				justify-content: center;
				width: 30upx;
				height: 14upx;
				line-height: 1;
				margin-left: 4upx;
				font-size: 26upx;
				color: #888;
				&.active{
					color: $base-color;
				}
			}
			.xia{
				transform: scaleY(-1);
			}
		}
		.cate-item{
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100%;
			width: 80upx;
			position: relative;
			font-size: 44upx;
			&:after{
				content: '';
				position: absolute;
				left: 0;
				top: 50%;
				transform: translateY(-50%);
				border-left: 1px solid #ddd;
				width: 0;
				height: 36upx;
			}
		}
	}

	/* 分类 */
	.cate-mask{
		position: fixed;
		left: 0;
		top: var(--window-top);
		bottom: 0;
		width: 100%;
		background: rgba(0,0,0,0);
		z-index: 95;
		transition: .3s;
		
		.cate-content{
			width: 630upx;
			height: 100%;
			background: #fff;
			float:right;
			transform: translateX(100%);
			transition: .3s;
		}
		&.none{
			display: none;
		}
		&.show{
			background: rgba(0,0,0,.4);
			
			.cate-content{
				transform: translateX(0);
			}
		}
	}
	.cate-list{
		display: flex;
		flex-direction: column;
		height: 100%;
		.cate-item{
			display: flex;
			align-items: center;
			height: 90upx;
			padding-left: 30upx;
 			font-size: 28upx;
			color: #555;
			position: relative;
		}
		.two{
			height: 64upx;
			color: #303133;
			font-size: 30upx;
			background: #f8f8f8;
		}
		.active{
			color: $base-color;
		}
	}

	/* 商品列表 */
	.goods-list{
		display:flex;
		flex-wrap:wrap;
		padding: 0 30upx;
		background: #fff;
		.goods-item{
			display:flex;
			flex-direction: column;
			width: 48%;
			padding-bottom: 40upx;
			&:nth-child(2n+1){
				margin-right: 4%;
			}
		}
		.image-wrapper{
			width: 100%;
			height: 330upx;
			border-radius: 3px;
			overflow: hidden;
			image{
				width: 100%;
				height: 100%;
				opacity: 1;
			}
		}
		.title{
			font-size: $font-lg;
			color: $font-color-dark;
			line-height: 80upx;
		}
		.price-box{
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding-right: 10upx;
			font-size: 24upx;
			color: $font-color-light;
		}
		.price{
			font-size: $font-lg;
			color: $uni-color-primary;
			line-height: 1;
			&:before{
				content: '￥';
				font-size: 26upx;
			}
		}
	}
	

</style>
